<template>
  <el-card>
    <template #header>
      <span>检测属性</span>
      <el-button @click="handleManualEntry" style="float: right" type="warning"
        >{{ manualEntryFlag ? "自动录入" : "手动录入" }}
      </el-button>
    </template>
    <el-descriptions :column="2">
      <el-descriptions-item label="身高">
        <template v-if="manualEntryFlag">
          <el-input type="number" v-model="userInfo.height">
            <template #append>cm</template>
          </el-input>
        </template>
        <template v-else>
          <ElInput readonly v-model="userInfo.height">
            <template #append>cm</template>
          </ElInput>
        </template>
      </el-descriptions-item>
      <el-descriptions-item label="体重">
        <template v-if="manualEntryFlag">
          <el-input type="number" v-model="userInfo.weight">
            <template #append>Kg</template>
          </el-input>
        </template>
        <template v-else>
          <ElInput readonly v-model="userInfo.weight">
            <template #append>Kg</template>
          </ElInput>
        </template>
      </el-descriptions-item>
    </el-descriptions>
  </el-card>
  <br />

  <el-alert
    :title="deviceStatus[bluetoothDevice.statusCode].message"
    :closable="false"
    :type="deviceStatus[bluetoothDevice.statusCode].type"
  />
  <el-card :body-style="{ textAlign: 'center' }">
    <el-button size="default" type="success" @click="handleRecordSave"
      >保存记录</el-button
    >&nbsp;&nbsp;
    <el-button
      size="default"
      type="danger"
      @click="connectToBluetooth"
      v-if="bluetoothDevice.statusCode !== '2'"
      >连接蓝牙 </el-button
    >&nbsp;&nbsp;
    <!--    <el-button size="default" type="danger" @click="connectToBluetooth" v-if="bluetoothDevice.statusCode === '2'"-->
    <!--      >断开连接</el-button-->
    <!--    >&nbsp;&nbsp;-->
  </el-card>

  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    v-model="bluetoothDialog.visible"
    :title="
      bluetoothDevice.deviceId ? '正在搜索蓝牙，请稍等' : '请选择一个蓝牙设备'
    "
    width="50%"
  >
    <ul>
      <li v-for="item in bluetoothList" v-bind:key="item.deviceId">
        <el-radio-group v-model="bluetoothDialog.deviceId">
          <el-radio :label="item.deviceId">{{ item.deviceName }}</el-radio>
        </el-radio-group>
      </li>
    </ul>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="bluetoothDialog.handleClose" type="warning"
          >关闭</el-button
        >
        <el-button type="success" @click="bluetoothDialog.handleOk"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
// 缓存的设备，刚登陆系统选择一次设备
import { computed, onMounted, reactive, ref } from "vue";
import { IBluetooth } from "@/model/BloodType";
import { ipcRenderer } from "electron";
import { ElNotification } from "element-plus";
import { Ihw700Cloud } from "@/model/TerminalType";

const props = defineProps<{
  modelValue: Partial<Ihw700Cloud>;
}>();
const emits = defineEmits(["save", "update:modelValue"]);

const userInfo = computed({
  get: () => {
    return props.modelValue || {};
  },
  set: (val) => {
    emits("update:modelValue", val);
  },
});
const manualEntryFlag = ref(false);
const handleManualEntry = () => {
  if (!manualEntryFlag.value) {
    manualEntryFlag.value = true;
    userInfo.value.measureTime = userInfo.value.measureTime || Date.now();
  } else {
    manualEntryFlag.value = false;
  }
};
const deviceStatus = reactive({
  "1": {
    message: "蓝牙未连接",
    type: "info" as "info" | "success" | "warning" | "error",
  },
  "2": {
    message: "蓝牙已连接",
    type: "success" as "info" | "success" | "warning" | "error",
  },
  "3": {
    message: "蓝牙已断开连接",
    type: "danger" as "info" | "success" | "warning" | "error",
  },
});

const changeDeviceStatus = (val: keyof typeof deviceStatus) => {
  bluetoothDevice.statusCode = val;
};
const bluetoothDevice = reactive<{
  statusCode: keyof typeof deviceStatus;
  deviceId: string;
  device: any;
}>({
  statusCode: "1",
  deviceId: "",
  device: null,
});
// 弹框选择蓝牙
const bluetoothDialog = reactive({
  visible: false,
  deviceId: bluetoothDevice.deviceId,
  handleClose: function () {
    bluetoothDialog.visible = false;
    ipcRenderer.send("bluetooth-select-done", "");
  },
  handleOk() {
    bluetoothDialog.visible = false;
    bluetoothList.value = [];
    bluetoothDevice.deviceId = bluetoothDialog.deviceId;
    ipcRenderer.send("bluetooth-select-done", bluetoothDevice.deviceId);
  },
});

const bluetoothList = ref<Array<IBluetooth>>();
const nav = window.navigator as any;
/**------------------------蓝牙相关start-------------------- */
// 0x1810  0x2A49血压功能  0x2A35血压测量
const BLUETOOTH_SERVICE = "0000ffe0-0000-1000-8000-00805f9b34fb";
const BLUETOOTH_SERVICE_CHARACTERISTIC = "0000ffe1-0000-1000-8000-00805f9b34fb";
// 点击开始测量，先搜索蓝牙，连接蓝牙，发送执行开始测量
const connectToBluetooth = async () => {
  manualEntryFlag.value = false;
  // 打开选择蓝牙的弹框
  bluetoothDialog.visible = true;
  bluetoothList.value = [];
  console.log("打开弹框，选择设备");
  try {
    console.log("开始搜索设备");
    bluetoothDevice.device = await nav.bluetooth.requestDevice({
      filters: [{ services: [BLUETOOTH_SERVICE] }],
      acceptAllDevices: false,
    });
    bluetoothDialog.visible = false;
    console.log("完成设备选择", bluetoothDevice.device);
    changeDeviceStatus("2");
    bluetoothDevice.device.addEventListener(
      "gattserverdisconnected",
      onDisconnected
    );
  } catch (error) {
    console.log(error);
    bluetoothDialog.visible = false;
    changeDeviceStatus("1");
    ElNotification({
      type: "error",
      title: "设备连接失败",
      message: "设备连接不成功，请确认终端蓝牙正常！",
    });
    ipcRenderer.send("cancel-bluetooth-select");
    console.log(1);
    return;
  }
  try {
    const bluetoothServer = await bluetoothDevice.device.gatt.connect();
    const bluetoothService = await bluetoothServer.getPrimaryService(
      BLUETOOTH_SERVICE
    );
    const characteristic = await bluetoothService.getCharacteristic(
      BLUETOOTH_SERVICE_CHARACTERISTIC
    );
    characteristic.addEventListener(
      "characteristicvaluechanged",
      handleBluetoothValueChange
    );
    await characteristic.startNotifications();
  } catch (error) {
    changeDeviceStatus("1");
    ElNotification({
      type: "error",
      title: "设备连接失败",
      message: "设备连接不成功，请确认终端蓝牙正常！",
    });
    ipcRenderer.send("cancel-bluetooth-select");
    console.log(`There was an error: ${error}`);
  }
};

const handleBluetoothValueChange = async (event: {
  target: { value: { buffer: any } };
}) => {
  const data = event.target.value.buffer;
  const val = ab2hex(data);
  const resValue = hexCharCodeToStr(val);
  console.log(resValue);
  let w: number | undefined;
  let h: number | undefined;
  if (resValue) {
    w = parseInt(resValue?.slice(1, 5));
    h = parseInt(resValue?.slice(7, 11));
  }
  if (h) {
    userInfo.value.height = h / 10;
  }
  if (w) {
    userInfo.value.weight = w / 10;
  }
  userInfo.value.measureTime = Date.now();
  handleRecordSave();
};
const ab2hex = (buffer: Iterable<number>) => {
  const hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ("00" + bit.toString(16)).slice(-2);
    }
  );
  console.log("hexArr", hexArr);
  return hexArr.join("");
};
const hexCharCodeToStr = (hexCharCodeStr: string) => {
  const trimedStr = hexCharCodeStr.trim();
  const rawStr =
    trimedStr.substr(0, 2).toLowerCase() === "0x"
      ? trimedStr.substr(2)
      : trimedStr;
  const len = rawStr.length;
  if (len % 2 !== 0) {
    alert("Illegal Format ASCII Code!");
    return "";
  }
  let curCharCode: number;
  const resultStr = [];
  for (let i = 0; i < len; i = i + 2) {
    curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
    // @ts-ignore
    resultStr.push(String.fromCharCode(curCharCode));
  }
  // return Math.round(parseFloat(resultStr.join("")) * 100) / 100
  return resultStr.join("");
};

onMounted(() => {
  ipcRenderer.on(
    "send-bluetooth-device-list",
    (event, dataList: Array<IBluetooth>) => {
      if (bluetoothDevice.deviceId !== "") {
        bluetoothDevice.device = dataList.find((item) => {
          return item.deviceId === bluetoothDevice.deviceId;
        });
        if (bluetoothDevice.device) {
          ipcRenderer.send("bluetooth-select-done", bluetoothDevice.deviceId);
        }

        return;
      } else {
        bluetoothList.value = dataList;
      }
    }
  );
});
// 断开连接
const onDisconnected = (data: any) => {
  console.log(data);
  bluetoothDevice.device = null;
  bluetoothDevice.deviceId = "";
  ipcRenderer.send("cancel-bluetooth-select");

  changeDeviceStatus("3");
};

const handleRecordSave = async () => {
  manualEntryFlag.value = false;
  emits("save");
};
</script>

<style scoped></style>
